﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Diagnostics;
using System.IO;
using EMeeting;
using Newtonsoft.Json.Linq;
using System.Data.SqlClient;
using System.Net.Sockets;
using System.Net;
using Newtonsoft.Json;

namespace MIMDesignShaft
{
    public partial class LoginForm : DevExpress.XtraEditors.XtraForm
    {
        private TextEditRemind remind = null;
        public LoginForm()
        {
            InitializeComponent();
            remind = new TextEditRemind();
            InitTextBoxRemind();
        }
        //忘记密码链接
        private void forgetHyperlinkLabelControl_Click(object sender, EventArgs e)
        {
            Process.Start("http://user.miningcloud.com.cn/forgetpwd");
        }
        //注册账号链接
        private void registerHyperlinkLabelControl_Click(object sender, EventArgs e)
        {
            Process.Start("http://user.miningcloud.com.cn/register");
        }
        void InitTextBoxRemind()
        {
            remind.InitAutoCompleteCustomSource(this.phoneNumberTextEdit);
        }
        private void loginSimpleButton_Click(object sender, EventArgs e)
        {
            string returnValues = ClientClass.clientMethodsLogin(phoneNumberTextEdit.Text, passwordTextEdit.Text);
            //（所需字段较少，故没有将json转换为对象，而是直接取元素值）
            JObject jObject = JObject.Parse(returnValues);
            //获取状态
            string status = jObject["status"].ToString();
            if (status == "success")
            {
                //保存正确的手机号码
                if (phoneNumberTextEdit.Text.Trim() != "")
                {
                    remind.Remind(phoneNumberTextEdit.Text.Trim());
                }
                //获取用户名
                string username = jObject["info"]["username"].ToString();
                //将登陆信息存入登陆日志
                loginLog();
                //判断是否进行邮箱验证，1：验证通过直接登录，2：没有验证进行验证
                string sql = string.Format("select * from MIMDesignShaft_VerifiedUser where verifiedPhoneNumber = '{0}'", phoneNumberTextEdit.Text.Trim());
                SqlDataReader dr = SqlHelper.ExecuteReader(sql,null);
                if (dr.Read())
                {
                    //通过验证，展示主界面
                    this.Hide();
                    Form1 mainForm = new Form1(username);
                    mainForm.ShowDialog();
                }
                else
                {
                    //未验证，展示验证界面
                    this.Hide();
                    EmailValidation validation = new EmailValidation(username, phoneNumberTextEdit.Text.Trim());
                    validation.ShowDialog();
                }
            }
            else if (status == "error")
            {
                string warn = jObject["msg"].ToString();
                if (warn == "用户不存在")
                {
                    MessageBox.Show(warn + "，请重新输入！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    phoneNumberTextEdit.Focus();
                }
                else if (warn == "密码不正确")
                {
                    MessageBox.Show(warn + "，请重新输入！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    passwordTextEdit.Focus();
                }
            }
        }
        /// <summary>
        /// 登陆日志
        /// </summary>
        public void loginLog()
        {
            //获取本地IP（使用socket与任意ip建立连接，获取本地终结点IP）
            string localIP;
            using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0))
            {
                socket.Connect("8.8.8.8", 65530);
                IPEndPoint endPoint = socket.LocalEndPoint as IPEndPoint;
                localIP = endPoint.Address.ToString();
            }
            string time = DateTime.Now.ToString();
            string sql = string.Format("insert into MIMDesignShaft_LoginLog(userPhoneNumber,userIP,loginTime) values('{0}','{1}','{2}')", phoneNumberTextEdit.Text.Trim(), localIP, time);
            SqlHelper.ExecuteNonQuery(sql, null);
        }

        private void phoneNumberTextEdit_MouseEnter(object sender, EventArgs e)
        {
            InitTextBoxRemind();
        }

        private void LoginForm_Load(object sender, EventArgs e)
        {
            //自动完成源(MaskBox对智能感知隐藏)
            phoneNumberTextEdit.MaskBox.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
            phoneNumberTextEdit.MaskBox.AutoCompleteSource = AutoCompleteSource.CustomSource;
        }

        private void LoginForm_Shown(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start(Application.StartupPath + @"\AutoUpdate.exe");
        }
    }
    /// <summary>
    /// 记录文本框输入过的内容
    /// </summary>
    public class TextEditRemind
    {
        private string[] array = null;
        /// <summary>
        /// 绑定数据源
        /// </summary>
        /// <param name="textEdit"></param>
        public void InitAutoCompleteCustomSource(TextEdit textEdit)
        {
            array = ReadTxt();
            if (array != null && array.Length > 0)
            {
                AutoCompleteStringCollection ACSC = new AutoCompleteStringCollection();
                for (int i = 0; i < array.Length; i++)
                {
                    ACSC.Add(array[i].Replace(" ", ""));
                }
                textEdit.MaskBox.AutoCompleteCustomSource = ACSC;
            }
        }
        string[] ReadTxt()
        {
            try
            {
                if (!File.Exists("Remind.txt"))
                {
                    FileStream fs = File.Create("Remind.txt");
                    fs.Close();
                    fs = null;
                }
                return File.ReadAllLines("Remind.txt", Encoding.Default);
            }
            catch { return null; }
        }
        public void Remind(string str)
        {
            StreamWriter writer = null;
            try
            {
                if (array != null && !array.Contains(str))
                {
                    writer = new StreamWriter("Remind.txt", true, Encoding.Default);
                    writer.WriteLine(str);
                }
            }
            finally
            {
                if (writer != null)
                {
                    writer.Close();
                    writer = null;
                }
            }
        }
    }

}